﻿using System;

using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// Simple example script of how a button can be scaled visibly when the mouse hovers over it or it gets pressed.
/// </summary>

[AddComponentMenu("UGUI/Interaction/Button Scale")]
public class UGUIButtonScale : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler
{
    public Transform tweenTarget;
    public Vector3 hover = new Vector3(1.05f, 1.05f, 1.05f);
    public Vector3 pressed = new Vector3(1.05f, 1.05f, 1.05f);
    public float duration = 0.2f;

    Vector3 mScale;
    bool mStarted = false;

    void Start()
    {
        if (!mStarted)
        {
            mStarted = true;
            if (tweenTarget == null) tweenTarget = transform;
            mScale = tweenTarget.localScale;
        }
    }

    void OnEnable() { }

    void OnDisable()
    {
        if (mStarted && tweenTarget != null)
        {
            UGUITweenScale tc = tweenTarget.GetComponent<UGUITweenScale>();

            if (tc != null)
            {
                tc.value = mScale;
                tc.enabled = false;
            }
        }
    }

    void OnPress(bool isPressed)
    {
        if (enabled)
        {
            if (!mStarted) Start();
            UGUITweenScale.Begin(tweenTarget.gameObject, duration, isPressed ? Vector3.Scale(mScale, pressed) : mScale).method = UGUITweener.Method.EaseInOut;
        }
    }

    void OnHover(bool isOver)
    {
        if (enabled)
        {
            if (!mStarted) Start();
            UGUITweenScale.Begin(tweenTarget.gameObject, duration, isOver ? Vector3.Scale(mScale, hover) : mScale).method = UGUITweener.Method.EaseInOut;
        }
    }

    void OnSelect(bool isSelected)
    {
        if (enabled)
        {
            OnHover(isSelected);
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        OnPress(true);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        OnPress(false);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        OnHover(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        OnHover(false);
    }

    public void OnSelect(BaseEventData eventData)
    {
        OnSelect(true);
    }

    public void OnDeselect(BaseEventData eventData)
    {
        OnSelect(false);
    }
}
